﻿using System;

using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Text;
using System.Globalization;
using System.Security.Cryptography;
using System.Drawing;

namespace IFD2
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblUTC.Text = TinyDAL.Get_DB_UTC_Time();//年月日间要用'/'分割，不能用'-'，否则JS不能将字符串转换为日期型！

            if (!IsPostBack)
            {
                Session["USER"] = "";
                Session["ACL"] = "";
                txtP_A_S_S.Text = "";
                hidP_A_S_S.Value = "";

                System.Web.Configuration.CompilationSection ds
                    = (System.Web.Configuration.CompilationSection)System.Configuration.ConfigurationManager.GetSection("system.web/compilation");
                if (ds.Debug)
                    Application["DEBUG"] = "1";
                else
                    Application["DEBUG"] = "0";
                
                string sConn;
                sConn = WebConfigurationManager.ConnectionStrings["IFD_DB"].ConnectionString.ToLower();
                //为避免各种版本意外影响生产库，限制几种特定版本：生产版run、练习版shadow、外部测试版beta、开发/内测版alpha
                if (sConn.IndexOf("initial catalog=ifd_run;") > 0)
                {
                    Application["VERTYPE"] = "RUN";
                    if (Application["DEBUG"].ToString() == "0")
                    {
                        lblVersion.Text = Application["VERSION"].ToString();
                        //lblVersion.ForeColor = Color.FromArgb(3, 55, 106);//#03376a
                    }
                    else
                    {
                        lblVersion.Text = "Debug Mode, Please check the 'Web.config' file!";
                        lbtnL_og_on.Enabled = false;
                    }
                }
                else if(sConn.IndexOf("initial catalog=ifd_shadow;") > 0)//每天与生产系统同步？
                {
                    Application["VERTYPE"] = "SHADOW";//Gamma
                    lblVersion.Text = Application["VERSION"].ToString() + " " + (string)base.GetLocalResourceObject("tipVerShadow.Text");
                    //lblVersion.ForeColor = Color.FromArgb(0, 255, 136);//#00ff88
                }
                else if (sConn.IndexOf("initial catalog=ifd_beta;") > 0)
                {
                    Application["VERTYPE"] = "BETA";
                    lblVersion.Text = Application["VERSION"].ToString() + " " + (string)base.GetLocalResourceObject("tipVerBeta.Text");
                    //lblVersion.ForeColor = Color.FromArgb(0, 255, 136);//#00ff88
                }
                else if (sConn.IndexOf("initial catalog=ifd_alpha;") > 0)
                {
                    Application["VERTYPE"] = "ALPHA";
                    lblVersion.Text = Application["VERSION"].ToString() + " " + (string)base.GetLocalResourceObject("tipVerAlpha.Text");
                    //lblVersion.ForeColor = Color.FromArgb(0, 255, 136);//#00ff88
                }
                else
                {
                    lbtnL_og_on.Enabled = false;
                    lblError.Text = "Invalid version or connection string, Please check the 'Web.config' file!";
                    return;
                }

                if (!ds.Debug && Request.ServerVariables["HTTPS"].ToUpper() == "OFF")//涉及密码和旅客信息的页面，在生产状态禁止非加密连接！建议全程加密
                {
                    lbtnL_og_on.Enabled = false;
                    lblError.Text = (string)base.GetLocalResourceObject("errHttps.Text"); //"Please use HTTPS to access this site!";
                    return;
                }

                //for testing
                //Application["DEBUG"] = "0";
                hidCulture.Value = CultureInfo.CurrentCulture.Name;
                hidAgent.Value = Request.UserAgent;

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "bll_sys_get_brief";
                SqlParameter para = cmd.Parameters.AddWithValue("@culture", CultureInfo.CurrentCulture.Name);//Request.UserLanguages[0]?
                DataTable myTab = new DataTable();
                int ret;
                try
                {
                    ret = TinyDAL.Exec(ref cmd, ref myTab);
                }
                catch(Exception ex)
                {
                    lblError.Text = (string)base.GetLocalResourceObject("errDbFailed.Text"); //"Can not connect to database!";
                    lbtnL_og_on.Enabled = false;
                    return;
                }
                lbtnL_og_on.Enabled = true;
                if (myTab.Rows.Count > 0)
                    litBrief.Text = myTab.Rows[0][0].ToString();
            }

            //测试时，显示上次验证码以测试验证码可读性
            //if (Application["DEBUG"].ToString() == "1" && Session["CHK_CODE"] != null)
            //    txtCheckCode.Text = Session["CHK_CODE"].ToString();
        }

        protected void lbtnL_og_on_Click(object sender, EventArgs e)
        {
            if (Session["FAIL_TIMES"] == null)
                Session["FAIL_TIMES"] = 0;
            if (System.Convert.ToInt16(Session["FAIL_TIMES"]) > 6)
            {
                lblError.Text = (string)base.GetLocalResourceObject("errManyFails.Text");
                lbtnL_og_on.Enabled = false;
                txtP_A_S_S.Text = "";
                hidP_A_S_S.Value = "";
                return;
            }

            if (Session["CHK_CODE"] == null)//长时间无操作导致应用/会话超时！
            { 
                Response.Redirect("~/Default.aspx");
                return;
            }

            //if (Application["DEBUG"].ToString() == "0")//压力测试时不判断是否机器人！压力测试直接测数据库，Web平时要全真测试！
            //{
                //if (Session["CHK_CODE"] == null)//不知为何最开始会丢失Session（偶尔）？
                //{
                //    lblError.Text = (string)base.GetLocalResourceObject("errRetry.Text"); //"Retry please.";
                //    txtCheckCode.Text = "";
                //    txtP_A_S_S.Text = "";
                //    hidP_A_S_S.Value = "";
                //    return;
                //}
                if (txtCheckCode.Text.ToLower() != Session["CHK_CODE"].ToString())
                {
                    lblError.Text = (string)base.GetLocalResourceObject("errChkCode.Text"); //"Please input the check code!";
                    txtCheckCode.Text = "";
                    txtP_A_S_S.Text = "";
                    hidP_A_S_S.Value = "";
                    return;
                }
            //}
            Session["CHK_CODE"] = ((char)10).ToString();// "K|DaI*K3^242L_JSD";

            txtCheckCode.Text = "";
            lblError.Text = "";

            string strU_I_D = txtU_I_D.Text.Trim().ToUpper();
            //txtPassword.Text = txtPassword.Text.Trim();
            hidP_A_S_S.Value = hidP_A_S_S.Value.Trim();
            if (!Pwd_Strength.Check(hidP_A_S_S.Value, strU_I_D))
            {
                lblError.Text = (string)base.GetLocalResourceObject("errWeakPass.Text"); //"Password is too weak!";
                txtP_A_S_S.Text = "";
                hidP_A_S_S.Value = "";
                return;
            }

            string pwd_hash="";
            string salt = "";
            DataTable myTab = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "bll_user_get_salt";
            SqlParameter para = cmd.Parameters.AddWithValue("@user", strU_I_D);
            try
            {
                TinyDAL.Exec(ref cmd, ref myTab);
                if (myTab.Rows.Count != 1)
                {
                    Session["FAIL_TIMES"] = System.Convert.ToInt16(Session["FAIL_TIMES"]) + 1;
                    lblError.Text = (string)base.GetLocalResourceObject("errFail.Text"); //"Invalid user id or password!";
                    txtP_A_S_S.Text = "";
                    hidP_A_S_S.Value = "";
                    return;
                }
                salt= myTab.Rows[0]["salt"].ToString().TrimEnd();
            }
            catch(Exception ex)
            {
                lblError.Text = "Database failed!";
                return;
            }

            //pwd_sha1 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1");
            //byte[] data = Encoding.ASCII.GetBytes(hidP_A_S_S.Value);//new byte[20];
            byte[] data = Encoding.ASCII.GetBytes(strU_I_D+hidP_A_S_S.Value+salt);//new byte[20];
            byte[] result;
            SHA256 sha = new SHA256CryptoServiceProvider();
            result = sha.ComputeHash(data);
            pwd_hash = BitConverter.ToString(result).Replace("-","");
            //pwd_sha1 = System.Convert.ToBase64String(result);//Encoding.ASCII.GetString(result);
            //lblHide.Text = pwd_sha1 + "/" + pwd_sha1.Length.ToString();
            //pwd_sha1 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1");

            string ip, proxy;
            if (Context.Request.ServerVariables["HTTP_VIA"] != null) // using proxy
            {
                ip = Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; // Return real client IP.
                proxy = Context.Request.ServerVariables["HTTP_VIA"];
            }
            else //not using proxy or can't get the Client IP
            {
                ip = Context.Request.ServerVariables["REMOTE_ADDR"]; //While it can't get the Client IP, it will return proxy IP(s).
                proxy = "";
            }
            if (ip.Length > 15)
                ip = ip.Substring(0, 15);

            //DataTable myTab = new DataTable();
            //SqlCommand cmd = new SqlCommand();
            cmd.Parameters.Clear();
            cmd.CommandText = "bll_user_logon";
            para = cmd.Parameters.AddWithValue("@user", strU_I_D);
            para = cmd.Parameters.AddWithValue("@pwd", pwd_hash);
            hidCulture.Value = pwd_hash;
            para = cmd.Parameters.AddWithValue("@ip_addr", ip);
            if(proxy == "")
                para = cmd.Parameters.AddWithValue("@attached", Request.UserAgent);
            else
                para = cmd.Parameters.AddWithValue("@attached", proxy +" | "+Request.UserAgent);

            //string user_role;
            StringBuilder role_acl = new StringBuilder("", 300);
            try
            {
                myTab.Clear();
                TinyDAL.Exec(ref cmd, ref myTab);
                if (myTab.Rows.Count != 1)
                {
                    Session["FAIL_TIMES"] = System.Convert.ToInt16(Session["FAIL_TIMES"]) + 1;
                    lblError.Text = (string)base.GetLocalResourceObject("errFail.Text"); //"Invalid user id or password!";
                    txtP_A_S_S.Text = "";
                    hidP_A_S_S.Value = "";
                    return;
                }
                //Session["TESTER"] = "1";//用于判断是否机器人的测试变量
                DataRow row1 = myTab.Rows[0];
                //user_role = row1["role"].ToString();
                //Session["LAST_LOGON"] = Convert.ToDateTime(row1["last_logon"]).ToString();
                //Session["LANG"] = "CHN-ZH";//row1["lang"].ToString();//网页识别语种！
                Session["AIRLINE"] = row1["airline"].ToString();
                Session["OFFICE"] = row1["office"].ToString();
                Session["GROUP_BOOK"] = Convert.ToBoolean(row1["group_book"]).ToString();
                Session["USER"] = row1["id"].ToString().Trim();//txtUserID.Text;
                Session["DCS_AIRPORT"] = row1["dcs_airport"].ToString().Trim();
                Session["OFFICE_TYPE"] = row1["office_type"].ToString().Trim();
                Session["DEFAULT_CURRENCY"] = row1["default_currency"].ToString().Trim();
                Session["PWD"] = pwd_hash;//用于支付请求签名！

                //存cookie何用？
                /*Response.Cookies["OFFICE"].Value = Session["OFFICE"].ToString();
                Response.Cookies["OFFICE"].Expires = DateTime.Now.AddDays(10);
                //Response.Cookies["OFFICE_ID"].Domain = "www.skytour.com"
                Response.Cookies["USER"].Value = txtUserID.Text;
                Response.Cookies["USER"].Expires = DateTime.Now.AddDays(10);
                //Response.Cookies["USER"].Domain = "www.skytour.com"*/


                cmd.CommandText = "bll_user_get_acl";
                cmd.Parameters.Clear();
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                myTab.Clear();
                TinyDAL.Exec(ref cmd, ref myTab);
                foreach (DataRow row in myTab.Rows)
                {
                    role_acl.Append(row["access_code"].ToString() + ",");
                }
                string ACL = role_acl.ToString();
                Session["ACL"] = "," + ACL;
                //检查用户是否有权限进入本界面
                int i = Session["ACL"].ToString().IndexOf("UA1");
                if (i < 0)
                {
                    lblError.Text = (string)base.GetLocalResourceObject("errUnauthorized.Text"); //"Unauthorized.";
                    Session["USER"] = "";
                    Session["ACL"] = "";
                    lbtnL_og_on.Enabled = false;
                    //Session["FAIL_TIMES"] = 7;
                    txtP_A_S_S.Text = "";
                    hidP_A_S_S.Value = "";
                    return;
                }

                cmd.Parameters.Clear();
                cmd.CommandText = "bll_lang_get_browser_default_lang";
                para = cmd.Parameters.AddWithValue("@culture", CultureInfo.CurrentCulture.Name);
                //Request.UserLanguages[0]
                try
                {
                    myTab.Clear();
                    TinyDAL.Exec(ref cmd, ref myTab);
                    if (myTab.Rows.Count == 1)
                    {

                        Session["LANG"] = myTab.Rows[0]["lang"].ToString();
                    }
                    else
                    {
                        //Session["LANG"] = CultureInfo.CurrentCulture.Name;
                        Session["LANG"] = "1";//英文
                    }
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                    txtP_A_S_S.Text = "";
                    hidP_A_S_S.Value = "";
                    return;
                }

                //mvMenu.ActiveViewIndex = 1;
                //lblUserName.Text = txtUserID.Text;
                //lblLastLogonTime.Text = Session["LAST_LOGON"].ToString();


                //Response.Redirect(Application["http"] + "/mainframe.htm");
                //string domain = TinyDAL.GetRequestDomain(HttpContext.Current.Request.Url.OriginalString);
                //Response.Redirect("http://" + HttpContext.Current.Request.Url.Host + ":" + Convert.ToInt32(Application["HTTP_PORT"].ToString()).ToString() + Application["WEB_PATH"].ToString() + "/mainframe.htm");
                txtP_A_S_S.Text = "";
                hidP_A_S_S.Value = "";
                Response.Redirect("~/Bulletin.aspx?islogonshow=1");
                //Server.Transfer("~/test.aspx");
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblError.Text = ex.Message;
                else
                    lblError.Text = (string)base.GetLocalResourceObject("errUnknown.Text"); //"Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
                txtP_A_S_S.Text = "";
                hidP_A_S_S.Value = "";
                return;
            }
        }
    }
}